package com.linewow.xhyy.nihaonew.receiver;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.reflect.TypeToken;
import com.linewow.xhyy.nihaonew.entity.jpush.JpushEntity;
import com.linewow.xhyy.nihaonew.event.MessageEvent;
import com.linewow.xhyy.nihaonew.net.util.Convert;

import org.simple.eventbus.EventBus;

import java.lang.reflect.Type;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by LXR on 2016/10/25.
 */
public class JPushReceiver extends BroadcastReceiver {
    private static final String TAG = "JPushReceiver";

    private NotificationManager nm;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (null == nm) {
            nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }

        Bundle bundle = intent.getExtras();

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
           Log.e(TAG, "JPush用户注册成功");

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
           Log.e(TAG, "自定义消息--->"+bundle.getString(JPushInterface.EXTRA_MESSAGE));


        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
           Log.e(TAG, "接受到推送下来的通知");

            receivingNotification(context,bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
           Log.e(TAG, "用户点击打开了通知");

//            openNotification(context,bundle);

        } else {
           Log.e(TAG, "Unhandled intent - " + intent.getAction());
        }
    }

    private void receivingNotification(Context context, Bundle bundle){
        String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
       Log.e(TAG, " title : " + title);
        String message = bundle.getString(JPushInterface.EXTRA_ALERT);
       Log.e(TAG, "message : " + message);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
       Log.e(TAG, "extras : " + extras);
        analysisExtras(extras);

    }

    private void analysisExtras(String extras) {
        Type jpushType=new TypeToken<JpushEntity>(){}.getType();
        JpushEntity entity=Convert.fromJson(extras,jpushType);
        if(entity.title!=null){
            MessageEvent messageEvent=new MessageEvent();
            switch (entity.title){
                case "回复":
                    messageEvent.setIndex(3);
                    break;
                case "赞":
                    messageEvent.setIndex(2);
                    break;
                case "关注":
                    messageEvent.setIndex(1);
                    break;
            }
            EventBus.getDefault().post(messageEvent,TAG);
        }

    }
}
